package org.wx.io.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description: 基于Nio 的文件复制
 * @author: wangxun
 * @createDate: 2021/8/10
 * @version: 1.0
 */
@Slf4j
public class NioFileCopy {

    public static final int CAPACITY = 1024 * 1024;

    public static void main(String[] args) {
        NioFileCopy nioFileCopy = new NioFileCopy();
        boolean b = nioFileCopy.copyFileTo("F:\\11.jpg", "F:\\1.jpg");
        log.info("复制结果：{}",b);
    }

    /**
     * 复制文件
     * @param destPath 目标文件路径
     * @param originalPath 原来文件路径
     * @return 成功还是失败
     */
    private boolean copyFileTo(String destPath,String originalPath){
        FileChannel destinationFileChannel = null;
        FileChannel originalChannel = null;
        try {
            RandomAccessFile accessFile = new RandomAccessFile(originalPath, "rw");
            File destFile = new File(destPath);
            if(!destFile.exists()){
                log.info("文件不存在");
                destFile.createNewFile();
            }


            RandomAccessFile destinationFile = new RandomAccessFile(destFile, "rw");

            destinationFileChannel = destinationFile.getChannel();
            log.info("获取文件通道");
            originalChannel = accessFile.getChannel();
            log.info("分配缓冲区");
            ByteBuffer allocate = ByteBuffer.allocate(CAPACITY);
            while (originalChannel.read(allocate) != -1) {


                log.info("开始复制");
                allocate.flip();
                destinationFileChannel.write(allocate);
                if(allocate.hasRemaining()){
                    break;
                }
                allocate.clear();
            }
            log.info("强制刷盘");
            destinationFileChannel.force(true);



        } catch (FileNotFoundException e) {
            log.error("文件访问出错:"+e.getMessage(),e);
        } catch (IOException e) {
            log.error("文件读取出错:"+e.getMessage(),e);
        }finally {
            try {
                originalChannel.close();
                destinationFileChannel.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return false;
    }
}
